package org.fight.config;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import org.fight.cache.FightCache;
import org.fight.cache.SessionCache;
import org.fight.manager.FightManager;
import org.fight.net.session.KcpSessionFactory;
import org.fight.plugin.NettyServerPlugin;

import com.sojoys.artifact.config.Constants;
import com.sojoys.artifact.config.Modules;
import com.sojoys.artifact.config.Plugins;
import com.sojoys.artifact.core.IConfig;
import com.sojoys.artifact.manager.ContextManager;
import com.sojoys.artifact.manager.PropManager;
import com.sojoys.artifact.plugin.actor.ActorPlugin;
import com.xiaoleilu.hutool.log.Log;
import com.xiaoleilu.hutool.log.LogFactory;

/**
 * Created by fxf on 2017/10/17.
 */
public class FightConfig implements IConfig {
	
	static final Log log = LogFactory.get(FightConfig.class);	

	@Override
	public void configConstant(Constants me) {
		// 设置使用的配置文件
		PropManager.use("app.properties");
		// SpringContext初始化
		ContextManager.me().init("app-init.xml");

		me.setSessionFactory(new KcpSessionFactory());

	}

	@Override
	public void configModules(Modules me) {
		// 逻辑Module注册
		me.add(new ModuleScan());
	}

	@Override
	public void configPlugin(Plugins me) {
		// 定时插件
		me.add(new NettyServerPlugin());
		// 停止Actor插件
		me.add(new ActorPlugin());
	}

	ScheduledExecutorService executorService = Executors.newScheduledThreadPool(1);

	ScheduledExecutorService fightExecutorService = Executors.newScheduledThreadPool(1);

	@Override
	public void afterServerStart() {

//		executorService.scheduleAtFixedRate(new Runnable() {
//			@Override
//			public void run() {
//				SessionCache.me().loop();
//			}
//		}, 1, 1, TimeUnit.MILLISECONDS);
		Thread t = new Thread(()->{
			while (true) {
				SessionCache.me().loop();
				try {
					Thread.sleep(1);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		},"sessionCache");
		t.start();
		
		fightExecutorService.scheduleAtFixedRate(new Runnable() {
			@Override
			public void run() {
				FightCache.loop();
			}
		}, 66, 66, TimeUnit.MILLISECONDS);
	}

	@Override
	public void beforeServerStop() {
		executorService.shutdown();
	}

	@Override
	public void startSucceed() {
		log.info("************ Server Start Finish ************");
	}
}
